package orm

import (
	"dongfeng_project/config"
	"dongfeng_project/models"
	"fmt"
	ch "github.com/ClickHouse/clickhouse-go/v2"
	"gorm.io/driver/clickhouse"
	"gorm.io/gorm"
	"log/slog"
	"os"
	"time"
)

var install *gorm.DB

func init() {
	db := GetDB()
	db.Set("gorm:table_options", "ENGINE=ReplacingMergeTree(created_at) ORDER BY id PRIMARY KEY id").AutoMigrate(&models.ArticleLink{})
	db.Set("gorm:table_options", "ENGINE=ReplacingMergeTree(created_at) ORDER BY id PRIMARY KEY id").AutoMigrate(&models.DedeWebsiteInterLink{})
	db.Set("gorm:table_options", "ENGINE=MergeTree ORDER BY uuid PRIMARY KEY uuid").AutoMigrate(&models.DedeFriendLink{})
	db.Set("gorm:table_options", "ENGINE=ReplacingMergeTree(created_at) ORDER BY (domain,created_at) PRIMARY KEY domain").AutoMigrate(&models.WebsiteDynamicAd{})
	db.Set("gorm:table_options", "ENGINE=ReplacingMergeTree(created_at) ORDER BY (ip) PRIMARY KEY ip").AutoMigrate(&models.IpStore{})
}

func Close() {
	// 程序结束时，关闭数据库连接
	if install != nil {
		sqlDB, _ := install.DB()
		if sqlDB != nil {
			sqlDB.Close()
		}
	}
}

func GetDB() *gorm.DB {
	if install == nil {
		install = connect()
	}
	return install
}
func connect() *gorm.DB {
	chDb := ch.OpenDB(&ch.Options{
		Addr: []string{fmt.Sprintf("%s:%d", config.GlobalConfig.Clickhouse.Host, config.GlobalConfig.Clickhouse.Port)},
		Auth: ch.Auth{
			Database: config.GlobalConfig.Clickhouse.Db,
			Username: config.GlobalConfig.Clickhouse.User,
			Password: config.GlobalConfig.Clickhouse.Password,
		},
		TLS: nil,
		Settings: ch.Settings{
			"max_execution_time": 60,
		},
		DialTimeout: 5 * time.Second,
		Debug:       config.GlobalConfig.Clickhouse.Debug,
	})

	db, err := gorm.Open(clickhouse.New(clickhouse.Config{
		Conn: chDb,
	}), &gorm.Config{})
	if err != nil {
		slog.Error(fmt.Sprintf("连接Clickhouse数据库失败，%s", err))
		os.Exit(1)
	}
	sqlDB, err := db.DB()
	if err != nil {
		slog.Error(fmt.Sprintf("连接数据库失败，%s", err))
		os.Exit(1)
	}
	sqlDB.SetMaxIdleConns(300)
	sqlDB.SetMaxOpenConns(500)
	sqlDB.SetConnMaxLifetime(1 * time.Hour)
	return db
}
